import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/components/Layout.vue'
import Home from '@/components/Home.vue'
import EmojiGenerator from '@/components/EmojiGenerator.vue'
import BatchGenerator from '@/components/BatchGenerator.vue'
import History from '@/components/History.vue'
import Profile from '@/components/Profile.vue'
import SharePage from '@/components/SharePage.vue'
import Settings from '@/components/Settings.vue'
import Feedback from '@/components/Feedback.vue'
import UserLogin from '@/components/UserLogin.vue'
import UserRegister from '@/components/UserRegister.vue'
import Generator from '@/views/Generator.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: UserLogin,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: UserRegister,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true }
      },
      {
        path: 'generate',
        name: 'Generator',
        component: Generator,
        meta: { requiresAuth: true }
      },
      {
        path: 'batch',
        name: 'BatchGenerator',
        component: BatchGenerator,
        meta: { requiresAuth: true }
      },
      {
        path: 'history',
        name: 'History',
        component: History,
        meta: { requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: { requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'settings',
        component: Settings,
        meta: { requiresAuth: true }
      },
      {
        path: 'feedback',
        name: 'feedback',
        component: Feedback,
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/share/:id',
    name: 'share',
    component: SharePage
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 需要登录的路由
  const authRequired = to.matched.some(record => record.meta.requiresAuth)
  
  if (authRequired && !token) {
    ElMessage.warning('请先登录')
    next('/login')
  } else {
    next()
  }
})

export default router